<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="查询内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="查询类型" clearable class="filter-item" style="width: 130px;margin-left: 10px;">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加管理员
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        下载数据
      </el-button>
      <el-checkbox v-model="listQuery.onlyWorking" style="margin-left: 10px" @change="getList">只显示在职</el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="#学号" prop="id" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" width="95">
        <template slot-scope="{row}">
          <span>{{ row.gender }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="密码" align="center" width="95">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.password }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="所属公司" align="center" min-width="100px">
        <template slot-scope="{row}">
          <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.com != null ? row.com.name : '暂无'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" min-width="120px">
        <template slot-scope="{row}">
          <span style="overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{ row.position }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Actions" align="center" width="270" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
<!--          <el-button type="primary" size="mini" @click="toDetail(row.id)">-->
<!--            详情-->
<!--          </el-button>-->
          <el-button icon="el-icon-chat-dot-round" size="mini" style="background-color: #409EFF;color: white" @click="toChat(row)" >私信</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="添加管理员用户" :visible.sync="editDialogFormVisible" style="width: 50%;margin: 0 auto;padding: 0">
      <el-form ref="registerForm" :rules="registerRules" :model="dialogTemp" label-position="left" label-width="70px" style="max-width: 400px;margin: 0 auto;">
        <el-form-item v-if="dialogStatus==='create'" label="用户名" prop="username">
          <el-input v-model="dialogTemp.username" />
        </el-form-item>
        <el-form-item v-if="dialogStatus==='create'" label="密码" prop="password">
          <el-input v-model="dialogTemp.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="toRegister">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="删除确认" :visible.sync="deleteDialogFormVisible" style="width: 450px;margin: 0 auto">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" /></span>
        删除数据将无法恢复
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="danger" @click="deleteData">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { fetchMemberList, registerAdmin, updateMember, deleteMember, fetchMemberByNames } from '@/api/member'
import { getPositionOptions, getPositionId } from '@/api/role'
import { fetchOrgByNames, fetchOrgNames } from '@/api/com'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { checkUsername, register } from '@/api/user'
const calendarTypeOptions = [
  { key: 'id', display_name: '学号' },
  { key: 'username', display_name: '用户名' },
  { key: 'name', display_name: '姓名' },
  { key: 'comName', display_name: '公司' }
]

const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '活跃': 'success',
        '离队': 'danger',
        '退役': 'info'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const validateRegisterUserName = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error('用户名不能为空'))
      } else {
        checkUsername(value).then(
          res => {
            if (res.data) {
              callback(new Error('用户名已存在'))
            } else {
              callback()
            }
          }
        )
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度要大于等于6'))
      } else {
        callback()
      }
    }
    return {
      value: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        type: '',
        title: '',
        page: 1,
        limit: 20,
        onlyWorking: true
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      genderOptions: ['男', '女'],
      statusOptions: ['活跃', '离队', '退役'],
      positionOptions: [],
      orgOptions: ['计算机服务队', '软件俱乐部', '自行车协会', '红会', '学生会'],
      showReviewer: false,
      dialogTemp: {
        id: -1,
        importance: 1,
        intro: '',
        title: '',
        type: '',
        status: '',
        password: '',
        positionList: []
      },
      registerRules: {
        username: [{ required: true, trigger: 'blur', validator: validateRegisterUserName }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
      },
      positionDialogFormVisible: false,
      positionTemp: [],
      editDialogFormVisible: false,
      deleteDialogFormVisible: false,
      deleteTemp: -1,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchMemberList(this.listQuery).then(res => {
        this.list = res.data.items
        this.total = res.data.total
        console.log()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //
      //   // Just to simulate the time of the request
      //   setTimeout(() => {
      //     this.listLoading = false
      //   }, 1.5 * 1000)
      // })
    },
    toDetail(id) {
      this.$router.push({ path: '/member/detail/' + id })
    },
    toChat(row) {
      if (row.id < this.$store.getters.id) { this.$router.push({ path: '/inform/p2p/' + row.id + '_' + this.$store.getters.id + '/' + new Date().getTime() }) } else { this.$router.push({ path: '/inform/p2p/' + this.$store.getters.id + '_' + row.id + '/' + new Date().getTime() }) }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleAddPosition() {
      this.positionDialogFormVisible = true
    },
    addPosition() {
      console.log(this.positionTemp)
      getPositionId(this.positionTemp[1]).then(
        res => {
          var i = 0
          for (; i < this.dialogTemp.positionList.length; i++) {
            if (this.dialogTemp.positionList[i].id === res.data.items.id) {
              break
            }
          }
          if (i >= this.dialogTemp.positionList.length) {
            this.dialogTemp.positionList.push(res.data.items)
          } else {
            Message({
              message: '不能重复添加职位',
              type: 'error',
              duration: 1000
            })
          }
          this.positionDialogFormVisible = false
          // this.positionTemp = []
        }
      )
    },
    deletePosition(index) {
      const list = { positionList: this.dialogTemp.positionList }
      console.log(list)
      list.positionList.splice(index)
      this.dialogTemp = Object.assign(list, this.dialogTemp)
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.dialogTemp = {
        intro: '',
        title: '',
        type: '',
        status: '',
        password: '',
        positionList: []
      }
    },
    toRegister() {
      this.$refs.registerForm.validate(
        valid => {
          if (valid) {
            const form = {
              username: this.dialogTemp.username,
              password: this.dialogTemp.password,
            }
            registerAdmin(form).then(
              res => {
                if (res.status === 200) {
                  this.isRegister = false
                  this.$message({
                    message: '注册成功',
                    duration: 2000
                  })
                }
              }
            )
          }
        }
      )
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.editDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      registerMember(this.dialogTemp).then(() => {
        this.getList()
        this.editDialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: 'Created Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleUpdate(row) {
      this.dialogTemp = Object.assign({}, row) // copy obj
      this.dialogTemp['positionList'] = []
      for (const i in row.roles) {
        this.dialogTemp.positionList.push({
          name: row.roles[i].org.name + row.roles[i].position,
          id: row.roles[i].id
        })
      }
      this.dialogStatus = 'update'
      this.editDialogFormVisible = true
    },
    handleDelete(row, index) {
      this.deleteDialogFormVisible = true
      this.deleteTemp = row.id
    },
    getAddDialogList() {
      if (this.addType === 'org') {
        fetchOrgByNames(this.listQuery.addDialog).then(
          response => {
            this.listQuery.addDialog.total = response.data.total
            this.gridData = response.data.items
            setTimeout(() => {
              this.listLoading = false
            }, 200)
          })
      } else {
        fetchMemberByNames(this.listQuery.addDialog).then(
          response => {
            console.log(response)
            this.listQuery.addDialog.total = response.data.total
            this.gridData = response.data.items
            setTimeout(() => {
              this.listLoading = false
            }, 200)
          })
      }
    },
    updateData() {
      const tempData = Object.assign({}, this.dialogTemp)
      updateMember(tempData).then(() => {
        this.editDialogFormVisible = false
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    deleteData() {
      deleteMember({ id: this.deleteTemp }).then(
        res => {
          this.getList()
          this.deleteTemp = -1
        }
      )
      this.deleteDialogFormVisible = false
    },
    handleFetchPv(pv) {
      // fetchPv(pv).then(response => {
      //   this.pvData = response.data.pvData
      //   this.dialogPvVisible = true
      // })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '社团', '职位', '状态', '简介']
        const filterVal = ['id', 'username', 'gender', 'org', 'position', 'status', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团成员表（总）'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="scss" scoped>
.el-icon-circle-plus-outline{
  font-weight: bold;
}
.el-icon-circle-plus-outline:hover{
  color: #5ec78f;
}
.el-icon-circle-plus-outline:active{
  color: #1a9b70;
}
</style>
